<?php

namespace App\Models\Common;

use App\Models\BaseModel;
use App\Models\Traits\KfSoftDeletes;
use App\Models\Traits\KfUid;
use Illuminate\Support\Facades\Cache;

class FsCompanyModel extends BaseModel
{
    use KfUid;
    use KfSoftDeletes;

    protected $table = 'fs_company';

    protected $fillable = [
        'departmentId',
        'name',
        'organizationId',
        'newId',
        'status',
    ];

    // 后续网页登录的organizationId
    const WEB_ORGANIZATION_ID = 100;

    // 测试部门departmentId
    const TEST_DEPARTMENT_ID = 'od-4d64e6af4d107dcd92cfa7a1d70a8500';

    const STATUS_ON  = 1;
    const STATUS_OFF = 0;

    const STATUS_TEXT = [
        self::STATUS_OFF => '禁用',
        self::STATUS_ON => '正常',
    ];

    public static function add(int $organizationId, string $departmentId, string $name)
    {
        return self::query()->updateOrCreate(['departmentId' => $departmentId], ['name' => $name, 'organizationId' => $organizationId]);
    }

    /**
     * 稽核机构新增
     * @param string $name
     * @param string $departmentId
     */
    public static function addV2(string $name, string $departmentId, int $status)
    {
        // fsCompany
        $new = FsCompanyModel::query()->updateOrCreate([
            'organizationId' => FsCompanyModel::WEB_ORGANIZATION_ID,
            'departmentId'   => $departmentId,
            'newId'          => 0,
        ], ['name' => $name, 'status' => $status]);

        // 删除缓存tag
        Cache::tags('quality_control_company_list')->flush();

        return $new;
    }

    /**
     * 供应商下的机构列表 - 仅查询web登录机构
     * @return array
     */
    public static function getCompanyLists(): array
    {
        return Cache::tags('quality_control_company_list')->remember('getCompanyLists', 60, function () {

            return self::query()
                       ->where('organizationId', FsCompanyModel::WEB_ORGANIZATION_ID)
                       ->where('status', self::STATUS_ON)
                       ->select('id', 'departmentId', 'name')
                       ->get()
                       ->toArray();
        });
    }

    /**
     * 获取机构名称
     * @param string $companyId
     * @return string
     */
    public static function getCompanyNameByDepartmentId(string $companyId): string
    {
        return collect(self::getCompanyLists())->keyBy('departmentId')[$companyId]['name'] ?? '';
    }

    /*
     * 根据部门id获取组织id
     */
    public static function getOrganizationIdByDepartmentId(string $departmentId): int
    {
        return (int)self::query()->where('departmentId', $departmentId)->value('organizationId');
    }
}
